package com.byx.chatclient.http;

import androidx.annotation.NonNull;

import com.byx.chatclient.entity.Result;
import com.byx.chatclient.factory.RetrofitFactory;
import com.google.gson.JsonElement;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * UploadFilesUtil
 *
 * @author Superb
 * @date 2021/4/6 22:12
 */
public class HttpFilesUtil {
    public static final int IMAGE = 100;
    public static final int AUDIO = 200;
    public static final int VIDEO  = 300;
    public static final int AVATAR =400;
    public static final int FILE= 500;

    public static void upload(File file, String mSenderId, UploadCallBack uploadCallBack, int fileType){
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"),file);
        String encodeName = null;
        try {
            encodeName = URLEncoder.encode(file.getName(),"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        MultipartBody.Part body = MultipartBody.Part.createFormData("file",encodeName,requestFile);
        Callback<Result<String>> resultCallback = new Callback<Result<String>>() {
            @Override
            public void onResponse(@NonNull Call<Result<String>> call, @NonNull Response<Result<String>> response) {
                Result<String> result = response.body();
                assert result != null;
                String url = result.getData();
                if (uploadCallBack != null){
                    uploadCallBack.onSuccess(url);
                }
            }

            @Override
            public void onFailure(@NonNull Call<Result<String>> call, @NonNull Throwable t) {
                if (uploadCallBack != null){
                    uploadCallBack.onFailure(t);
                }
            }
        };
        RetrofitFactory.getBean(ApiUrl.class)
                .upload(mSenderId,body,fileType)
                .enqueue(resultCallback);
    }

    public static void uploadFiles(List<File> files,String userId,UploadCallBack uploadCallBack,int type){
        List<MultipartBody.Part> parts = new ArrayList<>();
        for (File file : files) {
            RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"),file);
            String encodeName = null;
            try {
                encodeName = URLEncoder.encode(file.getName(),"utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            MultipartBody.Part body = MultipartBody.Part.createFormData("file",encodeName,requestFile);
            parts.add(body);
        }

        Callback<Result> resultCallback = new Callback<Result>() {
            @Override
            public void onResponse(@NonNull Call<Result> call, @NonNull Response<Result> response) {
                Result result = response.body();
                assert result != null;
                String url = ((JsonElement) result.getData()).getAsString();
                if (uploadCallBack != null){
                    uploadCallBack.onSuccess(url);
                }
            }

            @Override
            public void onFailure(@NonNull Call<Result> call, @NonNull Throwable t) {
                if (uploadCallBack != null){
                    uploadCallBack.onFailure(t);
                }
            }
        };
        RetrofitFactory.getBean(ApiUrl.class)
                .uploadFiles(userId,parts,VIDEO)
                .enqueue(resultCallback);
    }
    /**
     * 上传
     */
    public interface UploadCallBack {
        /**
         * 成功
         * @param url
         */
        void onSuccess(String url);

        /**
         * 失败
         * @param t
         */
        void onFailure(Throwable t);
    }

    public static void download(String localUrl, String remoteUrl, DownloadCallBack downloadCallBack){
        File file = new File(localUrl);
        if (file.exists()){
            file.delete();
        }
        RetrofitFactory.getBean(ApiUrl.class)
                .download(remoteUrl)
                .enqueue(new Callback<ResponseBody>() {
                    /**
                     * Invoked for a received HTTP response.
                     *
                     * <p>Note: An HTTP response may still indicate an application-level failure such as a 404 or 500.
                     * Call {@link Response#isSuccessful()} to determine if the response indicates success.
                     *
                     * @param call
                     * @param response
                     */
                    @Override
                    public void onResponse(@NonNull Call<ResponseBody> call, @NonNull Response<ResponseBody> response) {
                        if (response.isSuccessful()){
                            try {
                                long total = Objects.requireNonNull(response.body()).contentLength();//需要下载的总大小
                                long current = 0;
                                InputStream is = Objects.requireNonNull(response.body()).byteStream();
                                FileOutputStream fos = new FileOutputStream(file);
                                BufferedInputStream bis = new BufferedInputStream(is);
                                byte[] buffer = new byte[1024];
                                int len;
                                while ((len = bis.read(buffer)) != -1) {
                                    fos.write(buffer, 0, len);
                                    fos.flush();
                                    current += len;
                                    System.out.println("已经下载="+current+",共"+total);
                                }
                                fos.flush();
                                fos.close();
                                bis.close();
                                is.close();

                                downloadCallBack.onSuccess();
//                            EventBus.getDefault().post(MessageEvent.getInstance(EventType.DOWNLOAD_COMPLETE));
                            } catch (IOException e) {
                                e.printStackTrace();
                                downloadCallBack.onFailure(e);
                            }
                        }else {
                            downloadCallBack.onFailure(null);
                        }
                    }

                    /**
                     * Invoked when a network exception occurred talking to the server or when an unexpected exception
                     * occurred creating the request or processing the response.
                     *
                     * @param call
                     * @param t
                     */
                    @Override
                    public void onFailure(@NonNull Call<ResponseBody> call, @NonNull Throwable t) {
                        downloadCallBack.onFailure(t);
                    }
                });
    }

    /**
     * 下载
     */
    public interface DownloadCallBack{
        void onSuccess();

        void onFailure(Throwable t);
    }
}
